package com.kevin.Code.Array;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;

/**
 * @author Vinlee Xiao
 * @Classname MergeInterval
 * @Description Leetcode 56. 合并区间 中等难度 二刷自己的思路
 * @Date 2022/4/5 20:28
 * @Version 1.0
 */
public class MergeInterval {
    public static void main(String[] args) {
        int[][] arr = new int[][]{{1, 4}, {2, 3}};
        int[][] intervalArr = merge(arr);
        for (int[] i : intervalArr) {
            System.out.print(i[0] + " ");
            System.out.println(i[1]);
        }
    }

    /**
     * @param intervals
     * @return
     */
    public static int[][] merge(int[][] intervals) {
        Arrays.sort(intervals, new Comparator<int[]>() {
            @Override
            public int compare(int[] o1, int[] o2) {
                if (o1[0] == o2[0]) {
                    return o1[1] - o2[1];
                } else {
                    return o1[0] - o2[0];
                }
            }
        });
        List<int[]> result = new ArrayList<>();

        int row = intervals.length;
        int col = intervals[0].length;

        int start = intervals[0][0];
        int end = intervals[0][1];
        for (int i = 1; i < row; i++) {

            if (intervals[i][1] >= end && intervals[i][0] <= end) {
                end = intervals[i][1];
            } else if (intervals[i][0] > start && intervals[i][1] > end) {
                result.add(new int[]{start, end});
                start = intervals[i][0];
                end = intervals[i][1];
            }
        }

        result.add(new int[]{start, end});

        int[][] res = new int[result.size()][2];
        for (int i = 0; i < result.size(); i++) {
            res[i][0] = result.get(i)[0];
            res[i][1] = result.get(i)[1];
        }


        return res;
    }

}
